<script setup>
  import { ref, watch } from 'vue';
  import Codemirror from 'codemirror-editor-vue3';
  // import 'codemirror/lib/codemirror.css'; // 引入CodeMirror的样式文件
  import { python } from '@codemirror/lang-python';
  import { basicSetup } from 'codemirror';
  import { oneDark } from '@codemirror/theme-one-dark';
  import 'codemirror/theme/dracula.css'; // 引入你需要的主题样式，这里以dracula为例
  import { useMessage } from '/@/hooks/web/useMessage';
  import 'codemirror/mode/python/python.js'; // 引入Python语言模式

  import { EditorView } from '@codemirror/view'; // 引入自动换行功能
  import axios from 'axios';
  const { notification, createMessage } = useMessage();
  const props = defineProps({
    codes: {
      type: String,
      default: '',
    },
  });
  // 编辑器配置
  const localcode = ref(props.codes || '');
  // const extensions = [python(), basicSetup, oneDark];
  const extensions = {
    mode: 'python', // 设置语言模式为JavaScript
    //theme: 'dracula', // 设置主题为dracula
    theme: 'default',
    lineNumbers: true, // 显示行号
    lineWrapping: true, // 自动换行
    styleActiveLine: true, // 当前行背景高亮
    readOnly: false, // 是否只读
  };

  watch(
    () => props.codes,

    (newValue) => {
      console.log(newValue, 'newValue');
      localcode.value = newValue;
    },

    { immediate: true } // 立即执行一次，确保初始值同步
  );
  // 执行状态管理
  const output = ref('');
  const error = ref('');
  const isLoading = ref(false);
  const emit = defineEmits(['localcodeUpdate']);

  // API 配置
  const API_ENDPOINT = 'http://192.168.1.29:5000/run_python';

  // 执行代码逻辑
  const executeCode = async () => {
    if (!localcode.value.trim()) {
      error.value = '错误：代码不能为空';
      return;
    }

    isLoading.value = true;
    error.value = '';

    try {
      //@ts-ignore
      const response = await axios.post(
        API_ENDPOINT,
        {
          code: localcode.value,
        },
        {
          timeout: 15000, // 15秒超时
        }
      );

      // 处理成功响应
      if (response.data.output) {
        output.value = formatOutput(response.data.output.replace('\n', '').replace('\r', ''));
      } else if (response.data.error) {
        error.value = `服务器错误：${response.data.error}`;
      }
    } catch (err) {
      // 错误处理
      handleRequestError(err);
    } finally {
      isLoading.value = false;
    }
  };
  function removeHtmlTagsAndEntities(text) {
    // 替换 <br> 标签为空字符串

    let formattedText = text.replace(/<br\s*\/?>/gi, ''); // 使用 /gi 标志进行全局和大小写不敏感的替换

    // 替换 &nbsp; 实体为空字符串

    formattedText = formattedText.replace(/&nbsp;/g, ''); /*  */

    return formattedText;
  }
  // 格式化输出（保留换行和缩进）
  const formatOutput = (text) => {
    // return text.replace(/\n/g, "<br>").replace(/ /g, "&nbsp;");
    return removeHtmlTagsAndEntities(text);
  };

  const saveCodes = () => {
    emit('localcodeUpdate', localcode.value);
    createMessage.success('保存成功');
  };
  // 错误处理逻辑
  const handleRequestError = (err) => {
    if (err.code === 'ECONNABORTED') {
      error.value = '错误：请求超时（15秒）';
    } else if (err.response) {
      const status = err.response.status;
      error.value = `HTTP错误: ${status} - ${err.response.data?.error || '未知错误'}`;
    } else {
      error.value = `网络错误：${err.message}`;
    }
    output.value = '';
  };

  // 清空输出
  const clearOutput = () => {
    output.value = '';
    error.value = '';
  };
</script>

<template>
  <div class="python-editor">
    <!-- 代码编辑器 -->
    <div class="editor-header">
      <h2>Python 在线运行环境</h2>
      <div class="controls">
        <button @click="executeCode" :disabled="isLoading" class="run-button">
          {{ isLoading ? '执行中...' : '运行代码 ▶' }}
        </button>
        <button @click="saveCodes" class="save-button"> 保存代码 </button>
      </div>
    </div>

    <Codemirror style="height: 45vh" v-model:value="localcode" :options="extensions" />

    <!-- 执行结果输出 -->
    <div class="output-container" style="border-top: 3px solid #eee">
      <div class="output-header">
        <span>运行结果</span>
        <button @click="clearOutput" class="clear-button">清空结果</button>
      </div>
      <pre class="output-content" style="background: white" :class="{ 'has-error': error }">{{ output || error || '等待执行...' }}</pre>
    </div>
  </div>
</template>

<style scoped>
  .python-editor {
    max-width: 800px;
    margin: 2rem auto;
    padding: 20px;
    background: #f5f5f5;
    border-radius: 8px;
  }

  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
  }

  .run-button {
    background: #4caf50;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s;

    &:hover {
      background: #45a049;
    }

    &:disabled {
      background: #cccccc;
      cursor: not-allowed;
    }
  }
  .save-button {
    background: #70a2ee;
    color: white;
    border: none;
    padding: 8px 16px;
    margin-left: 5px;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s;
    .output-container {
      margin-top: 1.5rem;
      background: white;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }
  .output-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: #f8f9fa;
    border-bottom: 1px solid #eee;
  }

  .output-content {
    padding: 16px;
    min-height: 200px;
    white-space: pre-wrap;
    font-family: 'Courier New', monospace;

    &.has-error {
      color: #dc3545;
      background: #fff5f5;
    }
  }

  .clear-button {
    background: none;
    border: 1px solid #dc3545;
    color: #dc3545;
    padding: 4px 8px;
    border-radius: 3px;
    cursor: pointer;

    &:hover {
      background: #ffeef0;
    }
  }
</style>
